﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace DataTier.Repository
{
    /// <summary>
    /// Репозиторий для работы с пользователем
    /// </summary>
    public class UserRepository : RepositoryBase
    {
        public UserRepository()
        {

        }

        public UserRepository(IDbConnection connection)
            : base(connection)
        {

        }


        /// <summary>
        /// Регистрирует нового пользователя
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="hashPassword"></param>
        /// <param name="email"></param>
        /// <returns></returns>
        public User RegisterUser(string userName, string hashPassword, string email)
        {
            using (var dbcontext = CreateDataContext())
            {   
                var user = dbcontext.User.Where(u => u.Login.ToLower() == userName.ToLower()).FirstOrDefault();
                if (user != null)
                    throw new Exception("Такой пользователь уже существует!");

                user = new User()
                {
                    Login = userName,
                    Pass = hashPassword,
                    Email = email
                };

                dbcontext.AddToUser(user);
                dbcontext.SaveChanges();

                return user;
            }
        }


        /// <summary>
        /// Формирование Хэша пароля
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public string CalcHash(string password)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] data = System.Text.Encoding.ASCII.GetBytes(password);
            data = x.ComputeHash(data);
            return System.Text.Encoding.ASCII.GetString(data);
        }


        public bool IsExistsPassword(string password)
        {
            string hashPassword = CalcHash(password);
            using (var dbcontext = CreateDataContext())
            {
                var user = dbcontext.User.Where(u => u.Pass == hashPassword).FirstOrDefault();

                if (user != null)
                    return true;
                else
                    return false;
            }
        }



    }
}
